TokenGuard.canActivate   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 15
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 14
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 3
rs 9.7
c 0
b 0
f 0
1 9
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
2 9
import { TokensService } from '../tokens.service';
3
4
@Injectable()
5 9
export class TokenGuard implements CanActivate {
6 20
  constructor(private tokensService: TokensService) {}
7
8
  async canActivate(context: ExecutionContext): Promise<boolean> {
9 3
    const request = context.switchToHttp().getRequest<Request>();
10
11 3
    const tokenId = request.headers['x-api-token'];
12
13 3
    if (!tokenId) {
14 1
      throw new UnauthorizedException('Token is required');
15
    }
16
17 2
    try {
18 2
      await this.tokensService.consume(tokenId);
19 1
      return true;
20
    } catch (error) {
21 1
      throw new UnauthorizedException(error.message);
22
    }
23
  }
24
}
25